package com.aricksm.xuan.netretrofit;

import android.app.Activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends Activity {

    private static final String BASE_URL = "http://apis.baidu.com";
    private static final String API_KEY = "55533";//这里输入Api Key

    private Context context;

    private EditText et;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        //okHttp_asynchronousGet();
        //okHttp_synchronousGet();
        okHttp_postFromParameters();
    }

    private void initView() {
        context = this;
        et = (EditText) findViewById(R.id.edittext_activity_main);
        findViewById(R.id.button_activity_main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query();
            }
        });
    }

    private void query() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).build();
        PhoneService phoneService = retrofit.create(PhoneService.class);
        Call<PhoneResult> phoneResultCall = phoneService.getResult(API_KEY, et.getText().toString());
        phoneResultCall.enqueue(new Callback<PhoneResult>() {
            @Override
            public void onResponse(Call<PhoneResult> call, Response<PhoneResult> response) {
                if (response.isSuccessful()) {
                    Log.e("yuzhentao", "获取成功");
                    PhoneResult phoneResult = response.body();
                    if (phoneResult != null) {
                        PhoneResult.RetDataEntity retDataEntity = phoneResult.getRetData();
                        Toast.makeText(context, retDataEntity.getCity(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<PhoneResult> call, Throwable t) {
                Log.e("yuzhentao", "获取失败");
            }
        });
    }

    private void okHttp_asynchronousGet(){
        try {
            Log.e("","main thread id is "+Thread.currentThread().getId());
            String url = "http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            client.newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {

                }

                @Override
                public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                    // 注：该回调是子线程，非主线程
                    Log.e("","callback thread id is "+Thread.currentThread().getId());
                    Log.e("",response.body().string());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void okHttp_synchronousGet() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = "https://api.github.com/";
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(url).build();
                    okhttp3.Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        Log.e("net spose:", response.body().string());
                    } else {
                        Log.i("", "okHttp is request error");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 请求完整url：http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
                    String url = "http://api.k780.com:88/";
                    OkHttpClient okHttpClient = new OkHttpClient();
                    String json = "{'app':'weather.future','weaid':'1','appkey':'10003'," +
                            "'sign':'b59bc3ef6191eb9f747dd4e83c99f2a4','format':'json'}";
                    RequestBody formBody = new FormBody.Builder().add("app", "weather.future")
                            .add("weaid", "1").add("appkey", "10003").add("sign",
                                    "b59bc3ef6191eb9f747dd4e83c99f2a4").add("format", "json")
                            .build();
                    Request request = new Request.Builder().url(url).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    Log.e("post:fff", response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}